from aiogram import F, types
from aiogram_dialog import Dialog, DialogManager, StartMode, Window
from aiogram_dialog.widgets.kbd import Start
from aiogram_dialog.widgets.text import Const, Format
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.dialogs.data_getters import get_user_info
from app.bot.dialogs.dialog_state import AddBookSG, ClientSG, SelectBookSG
from app.database.requests import add_user, get_user


async def start(
    message: types.Message, dialog_manager: DialogManager, db_session: AsyncSession
):
    user_id = message.from_user.id
    username = message.from_user.username
    if not username:
        username = message.from_user.first_name

    user = await get_user(db_session, user_id)

    if not user:
        await add_user(db_session, telegram_id=user_id, username=username)

    await dialog_manager.start(ClientSG.start, mode=StartMode.RESET_STACK)


start_window = Window(
    Format(
        "Здравствуй, {event.from_user.username}!👋\n\n"
        "Я чат-бот Bam!Book 🎋\n\n"
        "Что я могу:\n"
        "•подобрать книгу в интересном для Вас жанре\n"
        "•найти произведение, подходящее Вам по уровню\n"
    ),
    Start(
        Const("Подобрать книгу"),
        id="select_book",
        state=SelectBookSG.select_genre,
    ),
    Start(
        Const("Добавить книгу"),
        id="add_book",
        when=F["is_admin"],
        state=AddBookSG.send_book_post,
    ),
    state=ClientSG.start,
    getter=get_user_info,
)


start_dialog = Dialog(start_window)
